<?php
/*
 * 得到tagged的文章，并缓存，提高访问速度
 */
require_once 'file_php.php';
require_once 'JG_Cache.php';
require_once 'Utils.php';

$kDebug = false;
$kEncryptEnable = false;
$kZipFile = false;

$kEncryptKey = "L";

$kMinCacheFileSize = 1024;
$kExpiration = 10 * 60;
$kPage = "page";
$kCountKeyword = "count";
$kTag = "tag";

$kServerFormatTxtUrl = "http://www.idreems.com/wordpress/?json=get_tag_posts&slug=%s&page=%s&count=%s";

if ($kDebug) {
    echo $kServerFormatTxtUrl . "</br>";
}

$zipfilename = Utils::getDataPath() . "result.zip";

$kDefaultCount = 30;
$kDefaultPage = 1;
$kDefaultTag = "场面话";

if ($kDebug) {
    echo $zipfilename . "</br>";
}

set_time_limit(0);

$page = $_GET[$kPage];
$page = (false == $page) ? $kDefaultPage : $page;
if ($kDebug) {
    echo $page . "</br>";
}
$count = $_GET[$kCountKeyword];
$count = (false == $count) ? $kDefaultCount : $count;
if ($kDebug) {
    echo $count . "</br>";
}

$tag = $_GET[$kTag];
$tag = (false == $tag) ? $kDefaultTag : $tag;

if ($kDebug) {
    echo $tag . "</br>";
}

$reqUrl = sprintf($kServerFormatTxtUrl, $tag, $page, $count);
if ($kDebug) {
    echo $reqUrl . "</br>";
    ;
}

// get cache data
$cache = new JG_Cache('cache'); // Make sure it exists and is writeable
if ($kDebug) {
    echo "JG_Cache" . "</br>";
}
$available = $cache->available($reqUrl, $kMinCacheFileSize, $kExpiration);
if ($kDebug) {
    echo "available" . $available . "</br>";
}

if (! $available) {
    if ($kDebug) {
        echo "getRemoteFile" . "</br>";
    }
    $data = file_php::getRemoteFile($reqUrl);
    
    if ($kEncryptEnable) {
        $data = Utils::xor_this($data, $kEncryptKey);
    }
    
    $filename = $cache->set($reqUrl, $data);
    
    if ($kDebug) {
        echo '$filename' . $filename . "</br>";
    }
    if ($kZipFile) {
        // create zip
        file_php::create_zip(array(
                $filename
        ), $zipfilename, true);
    }
}
if ($kZipFile) {
    $data = readfile($zipfilename);
} else {
    $data = $cache->get($reqUrl);
}

// 返回加密压缩的数据
echo $data;
?>